const randomstring = require('randomstring')
const querystring = require('querystring')
const crypto = require('crypto')

const {
  key
} = require('../config')

exports.genNonceStr = () => {
  return randomstring.generate(32)
}

exports.genSign = (_prepay) => {
  const StringA = querystring.stringify(
    // query 排序
    Object.keys(_prepay).sort().reduce(
      (obj, key) => { obj[key] = _prepay[key]; return obj }, 
      {}
      ),
      null,
      null,
      {
      // 注意中文和URL都不要编码
      encodeURIComponent(str) {
        return querystring.unescape(str)
      }
    }
  )
  const stringSignTemp = StringA + '&key=' + key
  const signValue = crypto.createHash('md5').update(stringSignTemp).digest('hex').toUpperCase()

  return signValue
}